package own.stu.jobgib.playown.vediodown.webo.model;

import com.google.gson.annotations.SerializedName;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import own.stu.jobgib.playown.vediodown.common.UrlUtil;
import own.stu.jobgib.playown.vediodown.common.model.BaseDataInfo;
import own.stu.jobgib.playown.vediodown.common.model.SimpleMediaItem;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@lombok.Data
public class WaterFallContent implements BaseDataInfo<ListItem, String> {

    @SerializedName("data")
    private Data data;

    @SerializedName("ok")
    private int ok;

    static String url_format = "https://weibo.com/ajax/profile/getWaterFallContent?uid=%d&cursor=%s";

    public static String getUrl(Long userId, String cursor) {
        return String.format(url_format, userId, cursor);
    }

    @Override
    public List<String> getExistUrls(String originUrl) {

        if (this.getData() == null) {
            return new ArrayList<>();
        }

        UrlUtil.UrlEntity urlEntity = UrlUtil.parse(originUrl);

        urlEntity.getParams().put("cursor", this.getData().getNextCursor());
        return Arrays.asList(UrlUtil.compose(urlEntity));
    }

    @Override
    public boolean hasNext() {
        String nextCursor = getData().getNextCursor();
        return StringUtils.isNotBlank(nextCursor) && Long.valueOf(nextCursor) > 0;
    }

    @Override
    public List<ListItem> getItemList() {
        return getData().getList();
    }

    @Override
    public SimpleMediaItem transFor(ListItem item) {

        SimpleMediaItem simpleMediaItem = new SimpleMediaItem();

        PageInfo pageInfo = item.getPageInfo();
        MediaInfo mediaInfo = pageInfo.getMediaInfo();

        simpleMediaItem.setDate(new Date(item.getCreatedAt()).getTime());
        simpleMediaItem.setBvId(pageInfo.getObjectId());
        String title = mediaInfo.getVideoTitle() == null ? mediaInfo.getKolTitle() : mediaInfo.getVideoTitle();
        simpleMediaItem.setTitle(title);
        simpleMediaItem.setCover(mediaInfo.getBigPicInfo().getPicBig().getUrl());

        return simpleMediaItem;
    }

    @Override
    public Long getUserId() {
        Long userId = 0L;

        List<ListItem> itemList = getItemList();
        if (CollectionUtils.isEmpty(itemList)) {
            return userId;
        }
        return itemList.get(0).getUser().getId();
    }
}